<!--codemirror-json格式化-->
<template>
  <textarea ref="textarea"/>
</template>

<script>
import CodeMirror from 'codemirror'
import 'codemirror/addon/lint/lint.css'
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/idea.css'
// require('script-loader!jsonlint')
import 'codemirror/mode/javascript/javascript'
// import 'codemirror/addon/lint/lint'
import 'codemirror/addon/lint/json-lint'

export default {
  name: 'JsonEditor',
  /* eslint-disable vue/require-prop-types */
  props: ['value'],
  data () {
    return {
      jsonEditor: false
    }
  },
  watch: {
    value (value) {
      const editorValue = this.jsonEditor.getValue();
      if (value !== editorValue) {
        // this.jsonEditor.setValue(JSON.stringify(this.value, null, 2))
        this.jsonEditor.setValue(this.value)
      }
    }
  },
  mounted () {
    this.jsonEditor = CodeMirror.fromTextArea(this.$refs.textarea, {
      lineNumbers: true,
      mode: {name: 'javascript', json: true},
      // 缩进单位，默认2
      indentUnit: 2,
      // 是否智能缩进
      smartIndent: true,
      // 显示行号
      styleActiveLine: true,
      // 代码折叠
      lineWrapping: true,
      // foldGutter: true,
      gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter', 'CodeMirror-lint-markers'],
      // CodeMirror-lint-markers是实现语法报错功能
      lint: true,
      // 括号匹配
      matchBrackets: true,
      theme: 'idea'
    });

    // this.jsonEditor.setValue(JSON.stringify(this.value, null, 2));
    this.jsonEditor.setValue(this.value);
    this.jsonEditor.on('change', cm => {
      this.$emit('changed', cm.getValue());
      this.$emit('input', cm.getValue());
    })
  },
  methods: {
    getValue () {
      return this.jsonEditor.getValue();
    }
  }
}
</script>

<style scoped>

</style>
